
function formatTime(date) {
  if(!date){
    date = new Date();
  }

  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds();


  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}
/*** 获取对应的下标数组 */
function getkey(obj,k){
  for (let key in obj) {
    for (let k1 in obj[key]) {
      if(k1==k){
        return obj[key][k1]
      }
    }
  }
}
function formatDistance(distance) {
  distance = +distance;
  return distance < 1000 ? Math.round(distance) + 'm' : (distance/1000).toFixed(1) + 'km';
}

function isPlainObject(obj) {
  for (var name in obj) {
    return false;
  }
  return true;
}
function toDate(number){  
    var n=number * 1000;  
    var date = new Date(n);  
    var Y = date.getFullYear() + '/';  
    var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '/';  
    var D = date.getDate()<10 ? '0'+date.getDate() : date.getDate();  
    return (Y+M+D)  
}  
function isPhoneNumber(num) {
  return /^1\d{10}$/.test(num);
}

function end_Time(second) {
  var days = Math.floor(second / 86400);
    var hours = Math.floor((second % 86400) / 3600);
    var minutes = Math.floor(((second % 86400) % 3600) / 60);
    var seconds = Math.floor(((second % 86400) % 3600) % 60);
    // var duration = days + "天" + hours + "小时" + minutes + "分" + seconds + "秒";
  var str = '';
  // if(year)str+=year+'-';
  // if(month)str+=month+'-';
  if(days)str+=days+' ';
  if(hours)str+=hours+':';
  if(minutes)str+=minutes+':';
  if(seconds)str+=seconds;
  return str
}

function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}


function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

module.exports = {
  formatTime: formatTime
}

const app = getApp()
let requestNum = 0;

// 拼接POST请求参数
function json2Form(json) {
  var str = [];
  for (var p in json) {
    str.push(encodeURIComponent(p) + "=" + encodeURIComponent(json[p]));
  }
  return str.join("&");
}

//网络请求old甜街版本封装
function request(urlStr = "", parameters = "", success, method = "GET", header = {
  'content-type': 'application/json'
}) {
  wx.request({
    url: app.globalData.BaseURL + urlStr + (method == "GET" ? "?" : "") + parameters,
    data: {
      'access_token': '6213ede986414d5fae5226304aeba411'
    },
    method: method, // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
    header: header ? header : "application/json", // 设置请求的 header
    success: function (res) {
//console.log(res);
      success(res);
    },
    fail: function () {
      // fail
      wx.hideToast();
    },
    complete: function () {
      // complete
      wx.hideToast();
    }
  })
}
const getRequest = (url, data, success) => {
  wx.showToast({
    title: "加载中",
    mask: true,
    icon: "loading",
    duration: 60000
  });
  requestNum++;  
  if(typeof(data)!='object'){
    data = {};
  }
  var key1 = wx.getStorageSync('key');
  data.key = key1;
  wx.request({
    url: app.globalData.BaseURL + url,
    data: data,
    method: "GET",
    header: {
      "Content-Type": "application/x-www-form-urlencoded",
      "userViewId": app.globalData.viewId,
    },
    success: res => {
      console.log(res,1231);
      var successData = res.data
      if (typeof successData != 'object') {

      var jsonStr = successData.replace(" ", "")
        jsonStr = jsonStr.replace(/\ufeff/g, "");
        var jj = JSON.parse(jsonStr);
        res.data = jj;
      }
      requestNum--;
//console.log(requestNu m, "requestNum--");
      if (requestNum == 0) {
        wx.hideToast();
      }
      if (res.data.code == 200) {
        success(res);
      } else if (res.data.code == 600) {
        // wx.hideToast();
        wx.navigateTo({
          url: "/pages/login/login"
        })
      } else {
        wx.showToast({
          title: res.data.msg ? res.data.msg:'成功',
          icon: 'none',
          duration: 2000
        })
        if (requestNum) { //如果还有其他请求没有结束，仍然loading
          wx.showToast({
            title: "加载中",
            mask: true,
            icon: "loading",
            duration: 60000
          });
        }
      }
    },
    fail: res => {
      requestNum--;
      wx.hideToast();
      wx.showToast({
        title: '网络请求错误！',
        icon: 'none',
        duration: 2000
      })
    },
  })
}
//验证是否设置支付密码
const is_yue_pass = () => {
  var data = {}
  var key1 = wx.getStorageSync('key');
  data.key = key1;
  var url = "index.php?act=member_account&op=get_paypwd_info";
  wx.request({
    url: app.globalData.BaseURL + url,
    data: data,
    method: "POST",
    header: {
      "Content-Type": "application/x-www-form-urlencoded",
      "userViewId": app.globalData.viewId,
    },
    success: res => {
      if (res.data.code == 200) {
        if (!res.data.datas.state) {
          wx.navigateTo({
            url: '/pages/set_password/set_password?type=paypwd'
          })
        }
      }
    }
    })
}
const postRequest = (url, data, success,gotourl, headerFlag) => {
  wx.showToast({
    title: "加载中",
    mask: true,
    icon: "loading",
    duration: 60000
  });
  requestNum++;

  if(typeof(data)!='object'){
    data = {};
  }
  var key1 = wx.getStorageSync('key');
  data.key = key1;
  wx.request({
    url: app.globalData.BaseURL + url,
    data: data,
    method: "POST",
    header: {
      "Content-Type": headerFlag ? "application/json;charset=utf-8" : "application/x-www-form-urlencoded",
      "userViewId": app.globalData.viewId,
    },
    success: res => {
      requestNum--;
      if (res.data.code == 200) {
        setTimeout(function(){
          success(res)
        },200)
        wx.hideToast();
      } else if (res.data.code == 400 && res.data.login == 0) { //未登录
        wx.hideToast();
        wx.navigateTo({
          url: "/pages/login/login"
        })
      } else {
        wx.showToast({
          title: res.data.msg?res.data.msg:'失败',
          icon: 'none',
          duration: 2000
        })
        if (gotourl){
          setTimeout(function () {
            wx.reLaunch({
              url: gotourl,
            })
          }, 1500)
        }
        if (requestNum) { //如果还有其他请求没有结束，仍然loading
          wx.showToast({
            title: "加载中",
            mask: true,
            icon: "loading",
            duration: 60000
          });
        }
      }
    },
    fail: res => {
      requestNum--;
      wx.showToast({
        title: '网络请求错误！',
        icon: 'none',
        duration: 2000
      })
    }
  })
}
const post1Request = (url, data, success, headerFlag) => {
  wx.showToast({
    title: "加载中",
    mask: true,
    icon: "loading",
    duration: 60000
  });
  requestNum++;

  if(typeof(data)!='object'){
    data = {};
  }
  var key1 = wx.getStorageSync('key');
  data.key = key1;
  wx.request({
    url: app.globalData.BaseURL + url,
    data: data,
    method: "POST",
    header: {
      "Content-Type":  "application/x-www-form-urlencoded",
      "userViewId": app.globalData.viewId,
    },
    success: res => {
      requestNum--;
      if (res.data.code == 200 || res.data.code == 400) {
        setTimeout(function(){
          success(res)
        },200)
        wx.hideToast();
      } else if (res.data.login == 0) { //未登录
        wx.hideToast();
        wx.navigateTo({
          url: "/pages/login/login"
        })
      } else {
        wx.showToast({
          title: res.data.msg?res.data.msg:'失败',
          icon: 'none',
          duration: 2000
        })
        if (requestNum) { //如果还有其他请求没有结束，仍然loading
          wx.showToast({
            title: "加载中",
            mask: true,
            icon: "loading",
            duration: 60000
          });
        }
      }
    },
    fail: res => {
      requestNum--;
      wx.showToast({
        title: '网络请求错误！',
        icon: 'none',
        duration: 2000
      })
    }
  })
}
//HUD 
//成功提示
function showSuccess(title = "成功啦", duration = 2500) {
  wx.showToast({
    title: title,
    icon: 'success',
    duration: (duration <= 0) ? 2500 : duration
  });
}
//loading提示
function showLoading(title = "请稍后", duration = 5000) {
  wx.showToast({
    title: title,
    icon: 'loading',
    mask: true,
    duration: (duration <= 0) ? 5000 : duration
  });
}
// 错误提示
function showErrorTost() {
  that.$wuxToast.show({
    type: 'text',
    timer: 1500,
    color: '#fff',
    text: '请求错误',
    success: () => console.log('请求错误')
  })
}
//隐藏提示框
function hideToast() {
  wx.hideToast();
}

const getUserPhone = (e, success) => {
  let type = e.currentTarget.dataset.type;
  if (e.detail.errMsg === "getPhoneNumber:ok") { //用户同意授权
//console.log("用户同意授权");
    getRequest('/api/wx/bindPhone', {
      openId: app.globalData.openId,
      sessionKey: app.globalData.sessionKey,
      encryptedData: e.detail.encryptedData,
      iv: e.detail.iv
    }, res => {
      wx.showToast({
        title: res.data.msg,
      })
      app.globalData.viewId = res.data.data.viewId;
      app.globalData.phone = res.data.data.phone;
//console.log(app.globalData.phone, "app.globalData.phone===")
      success(res);
    })
  }
}
//显示带取消按钮的消息提示框
function alertViewWithCancel(title = "提示", content = "消息提示", confirm, showCancel = "true") {
  wx.showModal({
    title: title,
    content: content,
    showCancel: showCancel,
    success: function (res) {
      if (res.confirm) {
        confirm();
      }
    }
  });
}
//显示不取消按钮的消息提示框
function alertView(title = "提示", content = "消息提示", confirm) {
  alertViewWithCancel(title, content, confirm, false);
}

function checkOpenId(that) {
//console.log(app.globalData.BaseURL)
  /*
   * 若openId为空，则重新获取openId
   */
  if (app.globalData.openId == "") {
    // 微信登录，获取openId
    wx.login({
      success: function (wxRes) {
//console.log("登陆成功");
//console.log(wxRes);
        //获取openid
        wx.request({
          url: app.globalData.ApiUrl + '/api/wx/login' + "?code=" + wxRes,
          method: 'GET',
          header: {
            "Content-Type": "application/x-www-form-urlencoded"
          },
          data: {
            'code': wxRes.code,
            'xcxid': app.globalData.xcxidStr
          },
          success: function(res) {
            var openId = res.data.data;
//console.log("openId===" + openId);
            app.globalData.openId = openId;
          },
          fail: function(res) {
//console.log("失败");
            app.globalData.openId = "";
            that.$wuxToast.show({
              type: 'text',
              timer: 1500,
              color: '#fff',
              text: '获取微信登录失败，请退出重试',
              success: () => console.log('获取微信登录失败，请退出重试')
            })
          }
        })
      },
      fail: function () {
//console.log("登录失败");
        that.$wuxToast.show({
          type: 'text',
          timer: 1500,
          color: '#fff',
          text: '微信登录失败，请退出重试',
          success: () => console.log('微信登录失败，请退出重试')
        })
      }
    });
  }
}


var countdown = 60;
// 倒计时
function settime(that) {
  if (countdown == 0) {
    that.setData({
      codeStr: '重新获取验证码',
      codeCanTouch: true
    })
    countdown = 60;
    return;
  } else {
    that.setData({
      codeStr: countdown + 's后重新获取',
      codeCanTouch: false
    })

    countdown--;
  }
  setTimeout(function () {
    settime(that)
  }, 1000)
}

/* 手机号验证 */
function validatePhone(phone) {
  var mbTest = /^(1)[0-9]{10}$/;
  if (!mbTest.test(phone)) {
    return "请输入正确手机号";
  }
  return "";
}
/** 计算对象数值的和 */
function sum(obj) {
  var s = 0; 
  for (let key in obj) {
    s += parseInt(obj[key])
  }
  return s;
};
//paraName 等找参数的名称
function getUrlParam(url, paraName) {
//console.log('util的url=====' + url);
//console.log('util的paraName=====' + paraName);


  var arrObj = url.split("?");
  if (arrObj.length > 1) {
    var arrPara = arrObj[1].split("&");
    var arr;
    for (var i = 0; i < arrPara.length; i++) {
      arr = arrPara[i].split("=");
      if (arr != null && arr[0] == paraName) {
        return arr[1];
      }
    }
    return "";
  } else {
    return "";
  }
}
module.exports = {
  formatTime: formatTime,
  isPlainObject: isPlainObject,
  isPhoneNumber: isPhoneNumber,
  formatDistance: formatDistance,
  ApiUrl: app.globalData.ApiUrl,

  formatTime: formatTime,
  json2Form: json2Form,
  request: request,
  showSuccess: showSuccess,
  showLoading: showLoading,
  hideToast: hideToast,
  alertViewWithCancel: alertViewWithCancel,
  alertView: alertView,
  checkOpenId: checkOpenId,
  settime: settime,
  validatePhone: validatePhone,
  getUrlParam: getUrlParam,
  // versionfunegt: versionfunegt,
  getRequest: getRequest,
  postRequest: postRequest,
  post1Request: post1Request,
  getUserPhone: getUserPhone,
  end_Time:end_Time,
  sum: sum,
  getkey: getkey,
  is_yue_pass: is_yue_pass
}


